from django.shortcuts import render,redirect
# 导入app01的models包
from app01 import models
# 分页组件封装
from app01.utils.pagination import Pagination
# form导入
from app01.utils.form import UserModelForm,PrettyModelForm,PrettyEditModelForm


def pretty_list(request):
    """ 靓号管理 """
    # 添加300条测试数据
    # for i in range(300):
    #     models.PrettyNum.objects.create(mobile="12345678909",price=19.9,level=1,status=1)

    # -level,表示desc排序,按级别排序
    # queryset = models.PrettyNum.objects.all().order_by('-level')
    # return render(request,'pretty_list.html',{'queryset':queryset})
    # 加搜索功能上面两行代码重写
    # 先定义一个空字典，把搜索内容添加到空字典，有值传值，并把值传到前端搜索框显示出来，没值搜索所有
    data_dict = {}
    search_data = request.GET.get('q',"")
    if search_data:
        data_dict["mobile__contains"] = search_data

    # 页码
    """
        <li><a href="?page=1">1</a></li>
        <li><a href="?page=2">2</a></li>
        <li><a href="?page=3">3</a></li>
        <li><a href="?page=4">4</a></li>
        <li><a href="?page=5">5</a></li>
    """
    queryset = models.PrettyNum.objects.filter(**data_dict).order_by("-level")
    page_object = Pagination(request,queryset,page_size=15)
    # page_queryset = page_object.page_queryset
    # page_string = page_object.html()
    context = {
               "search_data":search_data,
               "queryset": page_object.page_queryset,  # 分完页的数据
               "page_string":page_object.html()   # 页码
               }

    # 根据用户想要访问的页码，计算出起止位置,默认第一页起
    # page = int(request.GET.get('page', 1))
    # page_size = 10  # 定义一个变量，便于修改一页多少数据
    # start = (page - 1) * page_size
    # end = page + page_size

    # queryset = models.PrettyNum.objects.filter(**data_dict).order_by("-level")[page_object.start:page_object.end]
    # 计算数据库总条数
    # total_count = models.PrettyNum.objects.filter(**data_dict).order_by("-level").count()
    # # 计算数据页数divmod(),python内置方法：取商取余91%10 =（9，1）
    # total_page_count, div = divmod(total_count, page_size)
    # if div:
    #     # 数据库中获取值时，前取后不取，这里+1
    #     total_page_count += 1
    # 计算出，显示当前页的前5页和后5页
    # plus = 5
    # if total_page_count <= 2 * plus + 1:
    #     # 数据较少
    #     start_page = 1
    #     end_page = total_page_count + 1
    # else:
    #     # 数据较多>11页时
    #     # 当前页<5时（小极值）
    #     if page <= plus:
    #         start_page = 1
    #         end_page = 2 * plus + 1
    #     else:
    #         # 当前页大于5
    #         # 当前页+5 > 总页面
    #         if (page + plus) > total_page_count:
    #             start_page = total_page_count - 2 * plus
    #             end_page = total_page_count + 1
    #         else:
    #             start_page = page - plus
    #             end_page = page + plus + 1
    #
    # page_str_list = []
    # # 首页
    # page_str_list.append('<li ><a href="?page={}">首页</a></li>'.format(1))
    # # 上一页
    # if page > 1:
    #     prev = '<li><a href="?page={}">上一页</a></li>'.format(page - 1)
    # else:
    #     prev = '<li><a href="?page={}">上一页</a></li>'.format(1)
    # page_str_list.append(prev)
    #
    # # 页码
    # for i in range(start_page, end_page):
    #     if i == page:
    #         # 当前页高亮显示
    #         ele = '<li class="active"><a href="?page={}">{}</a></li>'.format(i, i)
    #     else:
    #         ele = '<li><a href="?page={}">{}</a></li>'.format(i, i)
    #     page_str_list.append(ele)
    #
    # # 下一页
    # if page < total_page_count:
    #     prev = '<li ><a href="?page={}">下一页</a></li>'.format(page + 1)
    # else:
    #     prev = '<li><a href="?page={}">下一页</a></li>'.format(total_page_count)
    # page_str_list.append(prev)
    # # 尾页
    # page_str_list.append('<li ><a href="?page={}">尾页</a></li>'.format(total_page_count))
    #
    # search_string = """
    #  <li>
    #      <form style="float: left;margin-left: -1px" method="get">
    #         <input name="page"
    #                style="position: relative;float: left;display: inline-block;width: 80px;border-radius: 0;"
    #                type="text" class="form-control" placeholder="页码">
    #         <button style="border-radius: 0" class="btn btn-default" type="submit">跳转</button>
    #     </form>
    # </li>
    # """
    # page_str_list.append(search_string)
    # # 添加mark_safe包，让前端安全读取
    # page_string = mark_safe("".join(page_str_list))

    return render(request,'pretty_list.html', context)

def pretty_add(request):
    """ 添加靓号 """
    if request.method == 'GET':
        form = PrettyModelForm()  # 实例化类得到对象
        return render(request,'pretty_add.html',{'form':form})
    # 用户POST提交数据，做数据校验 ，把PrettyModelForm实例化，得到form的数据，放在前端渲染
    form = PrettyModelForm(data=request.POST)
    # 如果数据正确则直接返回靓号列表页面
    if form.is_valid():
        form.save()
        return redirect("/pretty/list/")
    # 校验失败则提示错误信息
    return render(request,'pretty_add.html',{'form':form})

def pretty_edit(request,nid):
    """ 编辑靓号 """
    row_object = models.PrettyNum.objects.filter(id=nid).first()
    if request.method == 'GET':
        form = PrettyEditModelForm(instance=row_object)
        return render(request,'pretty_edit.html',{'form':form})
    # post
    form = PrettyEditModelForm(data=request.POST,instance=row_object)
    if form.is_valid():
        form.save()
        return redirect("/pretty/list/")
    return render(request,'pretty_edit.html',{'form':form})

def pretty_delete(request,nid):
    # filter查询
    models.PrettyNum.objects.filter(id=nid).delete()
    return redirect("/pretty/list/")